package blog.interceptor;

import blog.pojo.ResultVo;
import blog.pojo.User;
import blog.utils.JsonUtils;
import blog.utils.JwtUtils;
import blog.utils.RsaUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

/**
 * @author HuLin
 * @version 1.0
 * @date 2022/9/16 4:18
 */
public class LoginInterceptor implements HandlerInterceptor{


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//	  跨域请求会多一次option请求，不拦截放行
	  String method = request.getMethod();
	  if (method.equals("OPTIONS")){
	      return true;
	  }

//	  校验token
	  try{
	  String token = request.getHeader("token");
	  PublicKey publicKey = RsaUtils.getPublicKey(new ClassPathResource("key/rsa.pub").getInputStream());
	  JwtUtils.getInfoFromToken(token,publicKey, User.class);
	  //放行
		 return true;
	  }catch (Exception e){
	      //出错=》校验失败
		response.setContentType("application/json;charset=utf-8");
		String json = JsonUtils.toString(new ResultVo(403, "no power,login first"));
		response.getWriter().write(json);
	  }
	  return false;
    }
}
